package cz.proks.simplecalendarmanager.server.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import javax.servlet.http.HttpSession;

import cz.proks.simplecalendarmanager.server.Constants;
import cz.proks.simplecalendarmanager.shared.model.AccessToken;

public class ServletUtils {
	public static String getAccessTokenScopeKey(String scope) {
		return Constants.SESSION_OAUTH_ACCESS_TOKEN + "_" + scope;
	}
	
	public static AccessToken getAccessTokenFromSession(String scope, HttpSession session) {
		return (AccessToken) session.getAttribute(getAccessTokenScopeKey(scope));
	}
	
	public static void setAccessTokenToSession(String scope, AccessToken accessToken, HttpSession session) {
		session.setAttribute(getAccessTokenScopeKey(scope), accessToken);
	}
	
	public static void removeAccessTokenFromSession(String scope, HttpSession session) {
		session.removeAttribute(getAccessTokenScopeKey(scope));
	}
	
	public static String toString(InputStream stream) {
		StringBuilder sb = new StringBuilder();
		BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
		String line;
		
		try {
			while((line = reader.readLine()) != null) {
				sb.append(line).append("\n");
			}
		}
		catch (Exception e) {
			// NOP
		}
		
		return sb.toString();		
	}
}
